<template>
    <div class="supply">        <span class="titleStr">仓库信息</span>
        <el-progress :percentage="6" :format="format" :show-text="false"></el-progress>
        <p></p>

        <el-form :model="warehouse" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

            <el-row :gutter="20">
                <el-col :span="12" >
                    <el-form-item label="仓库名称" prop="name">
                        <el-input v-model="warehouse.name" placeholder="请输入仓库名称" clearable style="width: 350px" ></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12" >
                    <el-form-item label="仓库编码">
                        <el-input  placeholder="自动生成,无需填写" disabled style="width: 350px"></el-input>
                     </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12" >
                    <el-form-item label="仓库地址" prop="address">
                        <el-cascader style="width: 350px"
                                placeholder="请选择仓库地址"
                                v-model="selectedOptions"
                                :options="provinceCityCascade"

                                @change="handleChange">
                        </el-cascader>
                        <el-input
                                v-model="formLabelAlign.region"
                                placeholder="请填写详细地址"
                                style="width: 350px"
                                clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" >
                    <el-form-item label="仓库容量/件数" prop="capacity" label-width="120px">
                        <el-input v-model="warehouse.capacity" placeholder="请输入容量,只能是数字" clearable  style="width: 350px"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" >
                    <el-form-item label="最低库存预警" prop="minCount" label-width="120px">
                        <el-input v-model="warehouse.minCount" placeholder="请输入容量,只能是数字" clearable  style="width: 350px"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">

                    <el-form-item label="仓库性质">
                        <template>
                            <el-select v-model="warehouse.nature" placeholder="请选择仓库性质" style="width: 350px">
                                <el-option
                                        v-for="nature in warehouseNatureList"
                                        :key="nature.dictCode"
                                        :label="nature.dictLabel"
                                        :value="nature.dictLabel"
                                >
                                </el-option>
                            </el-select>
                        </template>
                    </el-form-item>

                </el-col>
            <el-col :span="12">
                <el-form-item label="最高库存预警" prop="maxCount" label-width="120px">
                    <el-input v-model="warehouse.maxCount" placeholder="请输入容量,只能是数字" clearable  style="width: 350px"></el-input>
                </el-form-item>
            </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12" >
                    <el-form-item label="租金" prop="rent" >
                        <el-input v-model="warehouse.rent" placeholder="请输入租金,只能是数字" clearable  style="width: 350px"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" >
                    <el-form-item label="仓库状态" prop="stop">
                        <el-radio-group v-model="warehouse.stop">
                            <el-radio label="启用" ></el-radio>
                            <br>
                            <el-radio label="停用" ></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>


                <el-form-item label="到期时间" prop="endTime">
                    <el-date-picker
                            v-model="warehouse.endTime"
                            type="datetime"
                            placeholder="请选择到期日期及时间"
                            style="cursor: pointer;">
                    </el-date-picker>
                </el-form-item>


            <span  class="titleStr">库管信息</span>
            <el-progress :percentage="6" :format="format" :show-text="false"></el-progress>


            <el-row :gutter="20">
                <el-col :span="12">
            <el-form-item label="仓库主管" prop="warehouseLeader" >
                <div class="e1" @click="dialogVisible1 = true">
                    <span id="person">{{ warehouse.warehouseLeader || '+ 选择成员' }}</span>
                </div>
            </el-form-item>

            <el-dialog
                    title="成员列表"
                    :visible.sync="dialogVisible1"
                    width="30%">
                <el-row :gutter="20">
                    <el-col :span="12">
                <div>
                    <el-tree
                            :data="companyDepartmentName"
                            node-key="id"
                            :props="defaultProps"
                            :default-expanded-keys="[1]"
                            @node-click="handleNodeClick">
                    </el-tree>
                </div>
                    </el-col>
                    <el-col :span="12">
                <!-- 显示选中部门的领导人信息 -->
                        <div>
                            <span>选中部门的员工列表:</span>
                            <br>
                            <div id="chooseLeader" v-for="(employee, index) in employeesInDepartment" :key="index">
                                <span @click="selectEmployee(employee)">{{employee.name}}</span>
                            </div>
                        </div>
                </el-col>
                </el-row>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible1 = false">取 消</el-button>
                    <el-button type="primary" @click="handleConfirm">确 定</el-button>

                </span>
            </el-dialog>
                </el-col>


                <el-col :span="12">
                    <el-form-item label="库管归属部门" prop="companyDepartmentId" label-width="120px">
                        <div class="e2">
                            <span id="person2">{{ warehouse.companyDepartmentId || '选择成员之后自动获取' }}</span>
                        </div>

                    </el-form-item>
                </el-col>
            </el-row>


            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="warehouse.phone" placeholder="请输入联系电话" clearable style="width: 350px"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import warehouseRouter from "@/router/warehouse";

    export default {
        name: "WarehouseAddView",
        data() {
            return {
                warehouselist: [],
                warehouse: {
                    name: '',
                    // code:'',
                    address: '',
                    capacity:'',
                    nature:'',//仓库性质存储
                    companyDepartmentId:'',
                    warehouseLeader:'',
                    phone: '',
                    minCount:'',
                    maxCount:'',
                    //product_management_id:'',
                    // instore_num:'',
                    // now_count:'',
                    rent:'',
                    endTime:'',
                    stop: '',
                    // enable:'',
                    delivery: false,
                },
                // warehouseNatureList:[{}],//仓库性质-->后端传输到此
                warehouseNatureList:[],
                provinceCityCascade: [],//仓库地址-->后端传输到此
                selectedOptions: [],//仓库地址相关选项
                detailedAddress: '',//input详细地址
                formLabelAlign: {
                    name: '',
                    region: '',
                    type: ''
                },
                dialogVisible1: false,//点击仓库主管弹出对话框
                dialogVisible2:false,//点击归属部门弹出对话框
                tempSelectedDepartment: '',//临时存储数据
                tempSelectedLeader: '',
                states: [{}],
                endTime:'',//到期时间所属
                //树形控件相关--添加仓库主管
                companyDepartmentName: [], // 存储从后端获取的部门数据
                companyDepartmentId:[],
                defaultProps: {
                    children: 'children',
                    label: 'companyDepartmentName' // 显示部门名称
                },
                employeeList:[],//存储从后端传输过来的所有员工
                employeesInDepartment:[],//存储过滤的(符合所选部门的id下的所有员工)员工们
                selectedLeader:'',
                brevityLeader: '',
                brevityCompanyDepartmentId:'',
                rules: {
                    name: [
                        //required必填属性,message显示信息,          trigger失去焦点
                        //min长度最小数量,max长度最大数量
                        {required: true, message: '请输入仓库名称', trigger: 'blur'},
                        {min: 3, max: 5, message: '名称在 3 到 5 个字符', trigger: 'blur'}
                    ],
                    address: [
                        {required: true,
                            validator: (rule, value, callback) => {
                                const selectedOptions = this.selectedOptions;
                                const detailedAddress = this.formLabelAlign.region;
                                if (selectedOptions.length === 0 && detailedAddress === '') {
                                    callback(new Error('请选择仓库地址并填写详细地址'));
                                } else if (selectedOptions.length > 0 && detailedAddress === '') {
                                    callback(new Error('请填写详细地址'));
                                } else if (selectedOptions.length === 0 && detailedAddress!== '') {
                                    callback(new Error('请选择仓库地址'));
                                } else {
                                    callback();
                                }
                            },
                            trigger: ['blur', 'change']
                        }
                    ],
                    stop: [
                        {required: true, message: '请选择仓库状态', trigger: 'change'}
                    ],
                    phone: [
                        {required: true, message: '联系电话不能为空', trigger: 'blur'},
                        {type: 'string', message: '联系电话必须是字符串类型', trigger: ['blur', 'change']}, // 通常不需要，因为v-model绑定的是字符串
                        {pattern: /^[1][3-9]\d{9}$/, message: '请输入有效的中国大陆手机号码', trigger: 'blur'} // 正则表达式验证手机号码
                    ],
                    warehouseLeader: [
                        { required: true, message: '请选择仓库主管', trigger: ['change', 'blur', 'input'] },
                    ],
                    companyDepartmentId: [
                        { required: true, message: '请选择库管归属部门', trigger: ['change', 'blur', 'input'] },
                    ],
                    endTime:[
                        { required: true, message: '请选择到期时间', trigger: 'blur' },
                    ],
                    capacity: [
                        { required: true, message: '请输入容量', trigger: 'blur' },
                        {
                            validator: (rule, value, callback) => {
                                if (value === null || value === '') {
                                    callback(new Error('请输入容量'));
                                } else if (Number.isNaN(Number(value))) {
                                    callback(new Error('格式为数字'));
                                } else if (!Number.isInteger(Number(value))) {
                                    callback(new Error('请输入整数'));
                                } else if (Number(value) <= 0) {
                                    callback(new Error('容量必须大于 0'));
                                } else {
                                    callback();
                                }
                            },
                            trigger: 'blur'
                        }
                    ],
                    minCount: [
                        { required: true, message: '请输入容量', trigger: 'blur' },
                        {
                            validator: (rule, value, callback) => {
                                if (value === null || value === '') {
                                    callback(new Error('请输入容量'));
                                } else if (Number.isNaN(Number(value))) {
                                    callback(new Error('格式为数字'));
                                } else if (!Number.isInteger(Number(value))) {
                                    callback(new Error('请输入整数'));
                                } else if (Number(value) <= 0) {
                                    callback(new Error('容量必须大于 0'));
                                } else {
                                    callback();
                                }
                            },
                            trigger: 'blur'
                        }
                    ],
                    maxCount: [
                        { required: true, message: '请输入容量', trigger: 'blur' },
                        {
                            validator: (rule, value, callback) => {
                                if (value === null || value === '') {
                                    callback(new Error('请输入容量'));
                                } else if (Number.isNaN(Number(value))) {
                                    callback(new Error('格式为数字'));
                                } else if (!Number.isInteger(Number(value))) {
                                    callback(new Error('请输入整数'));
                                } else if (Number(value) <= 0) {
                                    callback(new Error('容量必须大于 0'));
                                } else {
                                    callback();
                                }
                            },
                            trigger: 'blur'
                        }
                    ],
                    rent: [
                        { required: true, message: '请输入租金', trigger: 'blur' },
                        {
                            validator: (rule, value, callback) => {
                                if (value === null || value === '') {
                                    callback(new Error('请输入容量'));
                                } else if (Number.isNaN(Number(value))) {
                                    callback(new Error('格式必须全部为数字'));
                                } else if (!Number.isInteger(Number(value))) {
                                    callback(new Error('请输入整数'));
                                } else if (Number(value) <= 0) {
                                    callback(new Error('容量必须大于 0'));
                                } else {
                                    callback();
                                }
                            },
                            trigger: 'blur'
                        }
                    ]
                }
            };
        },
        //钩子函数,页面加载结束之后调出从数据库字典中取出来的仓库性质方法
        created() {
            //this.getWarehouseByid();
            this.getWarehouses();//查询仓库
            this.getWarehouseNatureList();//查询仓库性质
            this.getProvinceCityCascade();//查询仓库地址
            this.getCompanyDepartment();//查询所有部门
            this.getEmployeeList();//查询所有员工
        },
        methods: {
            // //通过id查仓库
            // getWarehouseByid(id) {
            //     this.$axios.get("manage/warehouse/" + id).then(response => {
            //         this.warehouse = response.data.data;
            //     })
            // },
            //查询所有员工
            getEmployeeList(){
                this.$axios.get("manage/employee/list").then(
                    response=>{
                        this.employeeList=response.data.data;
                    });
            },
            //查询仓库
            getWarehouses(){
                this.$axios.get("manage/warehouse/list").then(
                    response=>{
                        this.warehouselist=response.data.warehouselist;
                    });
            },
            //从数据库字典中获取仓库性质
            getWarehouseNatureList(){
                this.$axios.get("manage/scmDictData/dictDataList",{
                    params: { dataType: 'warehouse_nature' }
                }).then(
                    response=>{
                        this.warehouseNatureList=response.data.dataType;
                    })
                    .catch(error => {
                        console.error("获取仓库性质数据失败：", error);
                        alert("获取失败,请刷新重试")
                    });
            },
            //仓库性质改变事件
            handleNatureChange() {
                console.log(this.warehouse.nature);
            },
            //仓库地址
            getProvinceCityCascade(){
                this.$axios.get("manage/city/provinceCityCascade").then(
                    response=>{
                        this.provinceCityCascade = response.data.provinceCityCascade;
                    });
            },
            //查询所有部门
            getCompanyDepartment() {
                this.$axios.get("manage/companyDepartment/list")
                    .then(response => {
                        this.companyDepartmentList = response.data.data;
                        // 进行数据过滤
                        this.companyDepartmentName = this.companyDepartmentList.map(item => {
                            return {
                                companyDepartmentId:item.id,
                                companyDepartmentName:item.name,
                                leader:item.leader,
                                children: []
                            };
                        });
                    })
            },
            //树形控件相关--添加仓库主管
            // 处理节点点击事件
            handleNodeClick(companyDepartmentName) {
                if (companyDepartmentName && companyDepartmentName.companyDepartmentId) {
                    this.brevityCompanyDepartmentId = companyDepartmentName.companyDepartmentId;
                    // 调用获取该部门员工的方法
                    this.getEmployeesByDepartmentId(companyDepartmentName.companyDepartmentId);
                }
            },
            // 过滤出属于该部门的员工列表
            getEmployeesByDepartmentId(companyDepartmentId) {
                this.employeesInDepartment = this.employeeList.filter(employee => employee.companyDepartmentId === companyDepartmentId);
            },
            selectEmployee(employee) {
                this.tempSelectedLeader = employee.name;
            },
            // 点击确定按钮的处理函数
            handleConfirm() {
                if (!this.brevityCompanyDepartmentId) {
                    alert('请选择一个部门');
                    return;
                }
                const selectedNode = this.companyDepartmentName.find(node => node.companyDepartmentId === this.brevityCompanyDepartmentId);
                if (!this.tempSelectedLeader) {
                    alert('请选择员工');
                    return;
                }
                const personSpan = this.$refs.ruleForm.$el.querySelector('#person');
                const person2Span = this.$refs.ruleForm.$el.querySelector('#person2');
                personSpan.innerHTML = this.tempSelectedLeader;
                person2Span.innerHTML = selectedNode.companyDepartmentName;

                //给warehouse中的两条属性赋值
                this.warehouse.warehouseLeader = this.tempSelectedLeader;
                this.warehouse.companyDepartmentId = this.brevityCompanyDepartmentId;

                // 取消验证提示
                this.$refs.ruleForm.clearValidate(['warehouseLeader', 'companyDepartmentId']);
                this.dialogVisible1 = false;
            },
            //提交
            submitForm(formName) {
                this.$refs.ruleForm.validate((valid) => {
                    console.log(valid);
                    if (valid) {
                        let address = '';
                        // 获取从 el-cascader 中选择的地址部分
                        if (this.selectedOptions.length > 0) {
                            const findNodeByValue = (nodes, val) => {
                                for (let node of nodes) {
                                    if (node.value === val) {
                                        address += node.label;
                                        return;
                                    }
                                    if (node.children) {
                                        findNodeByValue(node.children, val);
                                    }
                                }
                            };
                            for (let item of this.selectedOptions) {
                                findNodeByValue(this.provinceCityCascade, item);
                            }
                        }
                        // 获取 input 中的详细地址部分
                        if (this.formLabelAlign.region) {
                            address += this.formLabelAlign.region;
                        }
                        this.warehouse.address = address;

                        // 转换仓库状态为布尔类型
                        this.warehouse.stop = this.warehouse.stop === "启用"? true : (this.warehouse.stop === "停用"? false : null);

                        // 转换到期时间为 'yyyy-MM-dd'T'HH:mm:ss.SSSX' 格式
                        if (this.warehouse.endTime) {
                            let year = this.warehouse.endTime.getFullYear();
                            let month = (this.warehouse.endTime.getMonth() + 1).toString().padStart(2, '0');
                            let day = this.warehouse.endTime.getDate().toString().padStart(2, '0');
                            let hours = this.warehouse.endTime.getHours().toString().padStart(2, '0');
                            let minutes = this.warehouse.endTime.getMinutes().toString().padStart(2, '0');
                            let seconds = this.warehouse.endTime.getSeconds().toString().padStart(2, '0');
                            let milliseconds = this.warehouse.endTime.getMilliseconds().toString().padStart(3, '0');
                            let timezone = 'Z'; // 可根据实际情况设置时区，'Z' 表示 UTC 时间
                            this.warehouse.endTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${timezone}`;
                        }

                        console.log("Warehouse object before sending request:", this.warehouse);

                        this.$axios.post("manage/warehouse/add", this.warehouse, {
                            headers: {
                                'Content-Type': 'application/json'
                            }

                        }).then(response => {
                            console.log(response.data);
                        }).catch(error => {
                            console.error("提交失败：", error);
                            if (error.response) {
                                console.error("Response status:", error.response.status);
                                console.error("Response data:", error.response.data);
                                console.error("Response headers:", error.response.headers);
                            } else if (error.request) {
                                console.error("No response received:", error.request);
                            } else {
                                console.error("Error setting up the request:", error.message);
                            }
                            alert("提交失败，请检查数据并刷新重试");
                        });
                    }
                });
            },
            //重置按钮
            resetForm(formName) {
                // 重置表单中带有验证规则的字段
                this.$refs[formName].resetFields();
                // 手动重置 selectedOptions 和 formLabelAlign.region
                this.selectedOptions = [];
                this.formLabelAlign.region = '';
                // 重置仓库主管相关内容
                this.warehouse.warehouseLeader = '';
                this.brevityLeader = '';
                // 重置库管归属部门相关内容
                this.warehouse.companyDepartmentId = '';
                this.brevityCompanyDepartmentId = '';
                // 重置名为 person2 的 span 中的内容
                this.$nextTick(() => {
                    this.$refs.ruleForm.$el.querySelector('#person2').innerHTML = '选择成员之后自动获取';
                });
                // 重置名为 person 的 span 中的内容
                this.$nextTick(() => {
                    this.$refs.ruleForm.$el.querySelector('#person').innerHTML = '+ 选择成员';
                });
                // 重置仓库容量相关输入
                this.warehouse.capacity = '';
                this.warehouse.minCount = '';
                this.warehouse.maxCount = '';
                this.warehouse.rent = '';
                // 重置仓库状态
                this.warehouse.stop = '';
                // 重置联系电话
                this.warehouse.phone = '';
                // 重置到期时间
                this.warehouse.endTime = '';
                // 重置仓库性质
                this.warehouse.nature = '';
                // 重置仓库名称
                this.warehouse.name = '';
            },
            formatter(row, column) {
                return row.address;
            },
            format(percentage) {
                return percentage === 100? '满' : `${percentage}%`;
            },
            handleChange(value) {
                this.selectedOptions = value;
            }
        }
    }
</script>

<!--样式设置-->
<style scoped>
    .titleStr {
        line-height: 30px;
        color: #409EFF;
    }
    .e1 {
        padding: 0;
        border: 1px dashed #666;
        width: 350px;
        border-radius: 2px;
        text-align: center;
        cursor: pointer;
        font-weight:lighter;
    }
    .e2 {
        padding: 0;
        border: 1px dashed #666;
        width: 350px;
        border-radius: 2px;
        text-align: center;
        cursor: pointer;
        font-weight:lighter;
    }
    #chooseLeader{
        cursor: pointer;
    }
    .supply{
        height: 740px;
    }
    lable{
        label-width:"120px"
    }
</style>